package tbalert.web.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import tbalert.hibernate3.Finder;
import tbalert.page.Pagination;
import tbalert.session.SessionProvider;
import tbalert.web.FrontConstants;
import tbalert.web.ResponseUtils;
import tbalert.web.SysConstants;
import tbalert.web.WebErrors;
import tbalert.web.entity.BaseInfo;
import tbalert.web.entity.Blxxk;
import tbalert.web.entity.Dpsyb;
import tbalert.web.entity.Dwdm;
import tbalert.web.entity.Fxpgb;
import tbalert.web.entity.HIVb;
import tbalert.web.entity.Jwzlqk;
import tbalert.web.entity.Process;
import tbalert.web.manager.BrxxMng;
import tbalert.web.manager.DwdmMng;

@Controller
@RequestMapping(value = "/brxx")
public class BrxxAct {
	private static final Logger log = LoggerFactory.getLogger(BrxxAct.class);

	@RequestMapping(value = "/list.do")
	public String list(ModelMap model, HttpServletRequest request,
			BaseInfo baseInfo, Boolean submit_flag, String hqlCondition,
			String djrqq, String djrqz, Integer pageNo, Integer pageSize) {
		if (pageSize == null) {
			pageSize = 20;
		}
		if (pageNo == null) {
			pageNo = 1;
		}
		baseInfo.setSubmit(submit_flag);
		Dwdm dwdm = (Dwdm) session.getAttribute(request, SysConstants.DWDM_KEY);
		String sjdwId = dwdm.getDwid();
		if (!StringUtils.isBlank(sjdwId) && (sjdwId.equals("00") || sjdwId.equals("bssa"))) {
			sjdwId = "";
		}
		Finder finder = Finder.create("from BaseInfo where djdw like '" + sjdwId + "%'");
		if (!StringUtils.isBlank(hqlCondition)) {
			finder.append(hqlCondition);
		} else {
			if (!StringUtils.isBlank(baseInfo.getKicid())) {
				finder.append(" and kicid like '%" + baseInfo.getKicid() + "%'");
			}
			if (!StringUtils.isBlank(baseInfo.getDjhm())) {
				finder.append(" and djhm like '%" + baseInfo.getDjhm() + "%'");
			}
			if (!StringUtils.isBlank(baseInfo.getBrxm())) {
				finder.append(" and brxm like '%" + baseInfo.getBrxm() + "%'");
			}
			if (!StringUtils.isBlank(djrqq)) {
				finder.append(" and djrq >= '" + djrqq + " 00:00:00'");
			}
			if (!StringUtils.isBlank(djrqz)) {
				finder.append(" and djrq <= '" + djrqz + " 23:59:59'");
			}
			if (baseInfo.getDjdw() != null
					&& !StringUtils.isBlank(baseInfo.getDjdw().getDwid())) {
				finder.append(" and djdw like '" + baseInfo.getDjdw().getDwid()
						+ "%'");
			}
		}
		if (baseInfo.getSubmit() != null) {
			finder.append(" and submit = "
					+ baseInfo.getSubmit().compareTo(false));
		} else {
			finder.append(" and submit=1");
		}
		finder.append(" order by djdw,kicid");
		Pagination p = brxxMng.findByFinder(finder, pageNo, pageSize);
		model.put("pagination", p);
		model.put("dwdms", dwdmMng.findBySjdw(sjdwId));
		model.put("query", baseInfo);
		model.put("djrqq", djrqq);
		model.put("djrqz", djrqz);
		return "/brxx/list";
	}

	@RequestMapping(value = "/add.do")
	public String add(ModelMap model, HttpServletRequest request) {
		model.put("constants", constants);
		return "/brxx/add";
	}

	@RequestMapping(value = "/edit.do")
	public String edit(HttpServletRequest request, ModelMap model, String kicid) {
		WebErrors errors = validateEdit(kicid, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		model.put("constants", constants);
		model.put("baseInfo", brxxMng.findByKicid(kicid));
		model.put("blxxk", brxxMng.findBlxxkById(kicid));
		return "/brxx/edit";
	}

	@RequestMapping(value = "/view.do")
	public String view(HttpServletRequest request, ModelMap model,
			String kicid, String brxm, Process process) {
		WebErrors errors = validateEdit(kicid, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		model.put("constants", constants);
		model.put("chain", process.getChain());
		model.put("kicid", kicid);
		model.put("brxm", brxm);
		process.adjustChain();
		if (StringUtils.isBlank(process.getChain())
				|| StringUtils.equals(process.getNextStep(), "baseInfo")) {
			model.put("baseInfo", brxxMng.findByKicid(kicid));
			Blxxk blxxk = brxxMng.findBlxxkById(kicid);
			model.put("blxxk", blxxk);
			process.adjustChain(blxxk);
			model.put("chain", process.getChain());
			return "brxx/view";
		} else if (StringUtils.equals(process.getNextStep(), "dpsyb")) {
			Dpsyb dpsyb = brxxMng.findDpsybById(kicid);
			if (dpsyb != null) {
				model.put("dpsyb", dpsyb);
				return "brxx/viewDpsyb";
			}
		} else if (StringUtils.equals(process.getNextStep(), "hivb")) {
			HIVb hivb = brxxMng.findHIVbById(kicid);
			if (hivb != null) {
				model.put("hivb", hivb);
				return "brxx/viewHivb";
			}
		} else if (StringUtils.equals(process.getNextStep(), "fxpgb")) {
			Fxpgb fxpgb = brxxMng.findFxpgbById(kicid);
			if (fxpgb != null) {
				model.put("fxpgb", fxpgb);
				return "brxx/viewFxpgb";
			}
		}
		errors.addError("系统错误：跳转页面没找到");
		return errors.showErrorPage(model);
	}

	@RequestMapping(value = "/save.do")
	public String save(HttpServletRequest request, ModelMap model,
			BaseInfo baseInfo, Blxxk blxxk, Jwzlqk jwzlqk, Dpsyb dpsyb,
			HIVb hivb, Fxpgb fxpgb, Process process) {
		if (StringUtils.equals(process.getCurStep(), "baseInfo")) {
			baseInfo.setSubmit(false);
			brxxMng.save(baseInfo);
			if (blxxk.getZlfl() != null && blxxk.getZlfl() == 2) {
				blxxk.setJwzlqk(jwzlqk);
			}
			brxxMng.save(blxxk);
			process.adjustChain(blxxk);
		} else if (StringUtils.equals(process.getCurStep(), "dpsyb")) {
			brxxMng.save(dpsyb);
		} else if (StringUtils.equals(process.getCurStep(), "hivb")) {
			brxxMng.save(hivb);
		} else if (StringUtils.equals(process.getCurStep(), "fxpgb")) {
			saveFxpgb(fxpgb);
		}
		return jump(request, model, baseInfo, process);
	}

	@RequestMapping(value = "/update.do")
	public String update(HttpServletRequest request, ModelMap model,
			BaseInfo baseInfo, Blxxk blxxk, Jwzlqk jwzlqk, Dpsyb dpsyb,
			HIVb hivb, Fxpgb fxpgb, Process process) {
		if (StringUtils.equals(process.getCurStep(), "baseInfo")) {
			brxxMng.update(baseInfo);
			if (blxxk.getZlfl() != null && blxxk.getZlfl() == 2) {
				blxxk.setJwzlqk(jwzlqk);
			}
			brxxMng.update(blxxk);
			process.adjustChain(blxxk);
		} else if (StringUtils.equals(process.getCurStep(), "dpsyb")) {
			brxxMng.update(dpsyb);
		} else if (StringUtils.equals(process.getCurStep(), "hivb")) {
			brxxMng.update(hivb);
		} else if (StringUtils.equals(process.getCurStep(), "fxpgb")) {
			updateFxpgb(fxpgb);
		}
		return jump(request, model, baseInfo, process);
	}

	@RequestMapping(value = "/delete.do")
	public String delete(HttpServletRequest request, ModelMap model,
			BaseInfo baseInfo, Boolean submit_flag, String hqlCondition,
			String djrqq, String djrqz, Integer pageNo, Integer pageSize) {
		WebErrors errors = validateDelete(baseInfo.getKicid(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		brxxMng.deleteById(baseInfo.getKicid());
		log.info("delete baseInfo kicid={}.", baseInfo.getKicid());
		return list(model, request, baseInfo, submit_flag, hqlCondition, djrqq,
				djrqz, pageNo, pageSize);
	}

	@RequestMapping(value = "/submit.do")
	public String submit(HttpServletRequest request, ModelMap model,
			String kicid) {
		WebErrors errors = new WebErrors(request);
		BaseInfo bean = brxxMng.changeStatus(kicid, true);
		if (bean != null) {
			return "brxx/success";
		} else {
			errors.addError("提交失败！未能找到KICID=" + kicid + "的病人信息卡");
			return errors.showErrorPage(model);
		}
	}

	@RequestMapping(value = "/reject.do")
	public String reject(HttpServletRequest request, ModelMap model,
			String kicid) {
		WebErrors errors = new WebErrors(request);
		BaseInfo bean = brxxMng.changeStatus(kicid, false);
		if (bean != null) {
			return "redirect:list.do";
		} else {
			errors.addError("退回失败！未能找到KICID=" + kicid + "的病人信息卡");
			return errors.showErrorPage(model);
		}
	}

	@RequestMapping(value = "/vldKicid.do")
	public void vldKicid(HttpServletRequest request,
			HttpServletResponse response, String kicid) throws JSONException {
		JSONObject json = new JSONObject();
		if (StringUtils.isBlank(kicid) || brxxMng.kicidExist(kicid)) {
			json.put("success", false);
		} else {
			json.put("success", true);
		}
		ResponseUtils.renderJson(response, json.toString());
	}

	@Autowired(required = true)
	private BrxxMng brxxMng;
	@Autowired(required = true)
	private DwdmMng dwdmMng;
	@Autowired(required = true)
	private FrontConstants constants;
	@Autowired(required = true)
	private SessionProvider session;

	private Fxpgb saveFxpgb(Fxpgb fxpgb) {
		if (fxpgb.getPart1() != null) {
			fxpgb.getPart1().setKicid(fxpgb.getKicid());
		}
		if (fxpgb.getPart2() != null) {
			fxpgb.getPart2().setKicid(fxpgb.getKicid());
		}
		if (fxpgb.getPart3() != null) {
			fxpgb.getPart3().setKicid(fxpgb.getKicid());
		}
		if (fxpgb.getPart4() != null) {
			fxpgb.getPart4().setKicid(fxpgb.getKicid());
		}
		if (fxpgb.getPart5() != null) {
			fxpgb.getPart5().setKicid(fxpgb.getKicid());
		}
		if (fxpgb.getPart6() != null) {
			fxpgb.getPart6().setKicid(fxpgb.getKicid());
		}
		return brxxMng.save(fxpgb);
	}

	private void updateFxpgb(Fxpgb fxpgb) {
		if (fxpgb.getPart1() != null) {
			fxpgb.getPart1().setKicid(fxpgb.getKicid());
		}
		if (fxpgb.getPart2() != null) {
			fxpgb.getPart2().setKicid(fxpgb.getKicid());
		}
		if (fxpgb.getPart3() != null) {
			fxpgb.getPart3().setKicid(fxpgb.getKicid());
		}
		if (fxpgb.getPart4() != null) {
			fxpgb.getPart4().setKicid(fxpgb.getKicid());
		}
		if (fxpgb.getPart5() != null) {
			fxpgb.getPart5().setKicid(fxpgb.getKicid());
		}
		if (fxpgb.getPart6() != null) {
			fxpgb.getPart6().setKicid(fxpgb.getKicid());
		}
		brxxMng.update(fxpgb);
	}

	private String jump(HttpServletRequest request, ModelMap model,
			BaseInfo baseInfo, Process process) {
		model.put("constants", constants);
		model.put("chain", process.getChain());
		model.put("baseInfo", baseInfo);

		process.adjustChain();
		if (StringUtils.equals(process.getNextStep(), "baseInfo")) {
			return edit(request, model, baseInfo.getKicid());
		} else if (StringUtils.equals(process.getNextStep(), "dpsyb")) {
			Dpsyb dpsyb = brxxMng.findDpsybById(baseInfo.getKicid());
			if (dpsyb != null) {
				model.put("dpsyb", dpsyb);
				return "brxx/editDpsyb";
			} else {
				return "brxx/addDpsyb";
			}
		} else if (StringUtils.equals(process.getNextStep(), "hivb")) {
			HIVb hivb = brxxMng.findHIVbById(baseInfo.getKicid());
			if (hivb != null) {
				model.put("hivb", hivb);
				return "brxx/editHivb";
			} else {
				return "brxx/addHivb";
			}
		} else if (StringUtils.equals(process.getNextStep(), "fxpgb")) {
			Fxpgb fxpgb = brxxMng.findFxpgbById(baseInfo.getKicid());
			if (fxpgb != null) {
				model.put("fxpgb", fxpgb);
				return "brxx/editFxpgb";
			} else {
				return "brxx/addFxpgb";
			}
		} else if (StringUtils.equals(process.getNextStep(),
				Process.SUCCESS_PAGE)) {
			return "brxx/success";
		} else if (StringUtils.equals(process.getNextStep(), "submit.do")) {
			return submit(request, model, baseInfo.getKicid());
		}
		WebErrors errors = new WebErrors(request);
		errors.addError("系统错误：跳转页面没找到");
		return errors.showErrorPage(model);
	}

	private WebErrors validateEdit(String id, HttpServletRequest request) {
		WebErrors errors = new WebErrors(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateDelete(String kicid, HttpServletRequest request) {
		WebErrors errors = new WebErrors(request);
		if (vldExist(kicid, errors)) {
			return errors;
		}
		return errors;
	}

	private boolean vldExist(String kicid, WebErrors errors) {
		if (errors.ifNull(kicid, "kicid")) {
			return true;
		}
		BaseInfo entity = brxxMng.findByKicid(kicid);
		if (errors.ifNotExist(entity, BaseInfo.class, kicid)) {
			return true;
		}
		return false;
	}
}
